#!/usr/bin/perl
use strict;
use warnings;
use Encode;
    
use WebService::GData::YouTube;
use WWW::YouTube::Download;

# Build a list of titles+id from the playlist
# Check if something got deleted or added in our dir
# Add mp3 tags
# Download the flvs first, THEN convert them :P

### Config  ###
my $destination_dir = "/Users/alex/Documents/Dropbox/Arc/music"; # Put the files in a dropbox/Gdrive folder for best results :)
my $youtube_user = "alexutv";
my $tmp_dir = "/tmp";
my $ffmepg_bin = "ffmpeg";
### /Config ###

my $client = WWW::YouTube::Download->new;
my $yt = new WebService::GData::YouTube();

## Iterate directory, put all the titles in a hash for later check of dupes
## /Iterate Dir


## Iterate playlists and sync to the directory, skipping known items
while(my $playlists = $yt->get_user_playlists("$youtube_user"))
{
    foreach my $playlist (@$playlists)
    {
        next if $playlist->title eq "Adrians playlist";
        
        while(my $videos = $yt->get_user_playlist_by_id($playlist->playlist_id))
        {
            foreach my $vid (@$videos)
            {
                
                my $vid_name = $vid->title;
                $vid_name =~ s#[^a-zA-Z0-9\s]*##g;
                $vid_name =  Encode::decode('utf8',$vid_name);
                my $playlist_name = Encode::decode('utf8',$playlist->title);
                
                unless (-e "$destination_dir/$vid_name.mp3")
                {
                    print "Downloading $destination_dir/$playlist_name/$vid_name.mp3\n";
                    $client->download($vid->video_id, {filename => "$tmp_dir/$vid_name.flv"});
                    system("mkdir \"$destination_dir/$playlist_name\"");
                    system("/opt/local/bin/ffmpeg -i \"$tmp_dir/$vid_name.flv\" \"$destination_dir/$playlist_name/$vid_name.mp3\"");
                    system("rm \"$tmp_dir/$vid_name.flv\"");
                }
            }
        }
    }
}

## /Iterate playlists

## Go through each file and check the CDDB database
## http://cpansearch.perl.org/src/JV/mp3getcddb-1.04/script/mp3getcddb ?
## /CDDB